<script setup lang="ts">
import { useRequest } from 'vue-hooks-plus'
import formateDate from '@/utils/formateDate'
import { deleteBaseCreateApi, getNoticePageApi, projectUpdateNoticesApi } from "@/api/project/index"
import { ElMessageBox } from 'element-plus';
import { BaseSuccessRespDTO } from '@/api/project/types';
import useUserStore from '@/store/modules/user';

const configList = ref([])
const total = ref(0)
const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const queryParams = ref<any>({
  page: 1,
  size: 20,
  title: '',
  noticeType: 1,
  declareStartTime: null,
  declareEndTime: null,
  createdBy: userStore?.id,
})

const operType = {
  1: '项目申报',
  2: '项目预警',
}

// 表头
const columns = ref([
  {
    title: '序号',
    dataIndex: 'key',
    slotName: 'key',
    width: 48,
  },
  {
    title: '通知名称',
    minWidth: 330,
    dataIndex: 'title',
    slotName: 'title',
  },
  {
    title: '项目分类',
    minWidth: 200,
    dataIndex: 'projectTypeName',
  },
  {
    title: '申报时间',
    minWidth: 160,
    dataIndex: 'declareStartTime',
    slotName: 'declareStartTime',
  },
  {
    title: '已审核数量/申报总数',
    minWidth: 80,
    dataIndex: 'approveNumber',
    slotName: 'approveNumber',
  },
  {
    title: '发送时间',
    minWidth: 110,
    dataIndex: 'updatedTime',
    slotName: 'updatedTime',
  },
  {
    title: '通知状态',
    minWidth: 80,
    dataIndex: 'publishStatus',
    slotName: 'publishStatus',
    tooltip: true,
  },
  {
    title: '操作',
    minWidth: 160,
    dataIndex: 'optional',
    slotName: 'optional',
  }
])

// 查询列表
const { run: getNoticePage, loading } = useRequest(getNoticePageApi, {
  // false 为自动执行
  manual: true,
  // 请求成功
  onSuccess: (data) => {
    configList.value = data.content || []
    total.value = data.totalElements
  },
})
// 查询列表
const { runAsync: delNotices, loading: delLoading } = useRequest(deleteBaseCreateApi, {
  // false 为自动执行
  manual: true,
  // 请求成功
  onSuccess: () => {
    ElMessage.success('删除成功')
    onSearch()
  },
})

// 发布消息
const { runAsync: updateNotices, loading: publishLoading } = useRequest(projectUpdateNoticesApi, {
  manual: true,
  onSuccess: (response: BaseSuccessRespDTO) => {
    console.log(response, 'response');

    if (response.isSuccess) {
      ElMessage({
        message: '发布成功',
        type: 'success',
      })

      onSearch()
    }
  }
})


onSearch()

// 过滤查询
function onSearch() {
  getNoticePage(queryParams.value)
}

// 分页
function pagetionSerach(params) {
  queryParams.value = {
    ...queryParams.value,
    ...params,
  }
  onSearch()
}

// 删除
const handleDelete = (record) => {
  ElMessageBox.confirm('是否确认删除？', "", {
    type: 'warning',
    confirmButtonClass: 'el-button--danger',
    confirmButtonText: '删除',
    loading: delLoading.value,
    beforeClose: async (action, instance, done) => {
      if (action === 'confirm') {
        const isTrue = await delNotices({ id: record.id })

        isTrue && done()
      } else {
        done()
      }
    }
  })
}

const linkToPage = (record) => {
  router.push({
    path: '/project/manage/publicList',
    query: {
      noticeId: record.id
    }
  })
}

const linkToDetails = (record) => {
  router.push({
    path: '/project/manage/noticesDetails',
    query: {
      id: record.id
    }
  })
}

const linkToCreate = () => {
  console.log('跳转页面》')
  router.push({
    path: '/project/manage/publishNotices',
    query: {
      type: route.query.type,
      projectNature: route.query.projectNature
    }
  })
}

const publicNotices = (row) => {
  // 二次确认弹框
  // ElMessageBox.confirm('是否确认发布？', "", {
  //   confirmButtonText: '发布',
  //   loading: publishLoading.value,
  //   type: 'warning',
  //   beforeClose: async (action, instance, done) => {
  //     if (action === 'confirm') {
  //       const { content, declareStartTime, declareEndTime, fileIds, id, title, projectType, statisticsYear, projectNature } = row
  //       const params = {
  //         projectNature,
  //         content,
  //         declareStartTime: formateDate(declareStartTime).format('YYYY-MM-DD'),
  //         declareEndTime: formateDate(declareEndTime).format('YYYY-MM-DD'),
  //         fileIds,
  //         id,
  //         title,
  //         projectType,
  //         statisticsYear,
  //         isDirectPublish: true
  //       }
  //       const isTrue = await updateNotices(params)
  //       done(isTrue)
  //     } else {
  //       done()
  //     }
  //   }
  // })
  router.push({ path: '/project/manage/publishNotices', query: { projectNature: row.projectNature, id: row.id } })
}

</script>

<template>
  <div class="app-container">
    <TableForm :pageSize="20" :data="configList" :columns="columns" :tableLoading="loading" :total-count="total"
      :hideLeftMenu="false" :hideRightSecondBtn="true" :showSearchIcon="false" :showToolBar="true"
      @refresh="pagetionSerach">
      <template #leftMenu="">
        <div>
          <el-button type="primary" @click="linkToCreate">发布申报通知</el-button>
        </div>
      </template>
      <template #key="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>
      <template #noticeType="{ record }">
        {{ operType[record.type] }}
      </template>
      <template #declareStartTime="{ record }">
        {{ formateDate(record.declareStartTime).format('YYYY.MM.DD') }} -
        {{ formateDate(record.declareEndTime).format('YYYY.MM.DD') }}
      </template>
      <template #updatedTime="{ record }">
        {{ formateDate(record.updatedTime).format('YYYY-MM-DD') }}
      </template>
      <template #publishStatus="{ record }">
        <div class="flex items-center">
          <span class="h-[6px] w-[6px] rounded-[3px] inline-block"
            :style="{ backgroundColor: record.publishStatus === 1 ? '#FF7D00' : '#00B42A' }"></span>
          <span class="text-14px ml-8px inline-block"
            :style="{ color: record.publishStatus === 1 ? '#FF7D00' : '#00B42A' }">
            {{ record.publishStatus === 1 ? '未发布' : '已发布' }}
          </span>
        </div>
      </template>\
      <template #approveNumber="{ record }">
        <span v-if="record.approveNumber || record.declareNumber">
          {{ record.approveNumber }} / {{ record.declareNumber }}
        </span>
        <span v-else>-</span>
      </template>
      <template #optional="{ record }">
        <el-button link type="primary" @click="linkToDetails(record)">详情</el-button>
        <el-button v-if='record.publishStatus === 1' link type="primary" @click="publicNotices(record)">发布</el-button>
        <el-button v-if="record.publishStatus === 1" link type="danger" @click="handleDelete(record)">删除</el-button>
        <el-button v-else link type="primary" @click="linkToPage(record)">审核</el-button>
      </template>
    </TableForm>
  </div>
</template>